<template>
  <div>
    <Spin :spinning="loading" tip="Loading...">
      <!-- 搜索 -->
      <!-- table -->
      <BreakSpace label="配件类型" :containerStyle="{ marginBottom: '10px' }" />
      <FormPanel ref="formPanel" :list="topFilterInit" :cols="2" :formType="'add'" labelWidth="100" :isSubmitBtn="false" />
      <BreakSpace label="配件列表" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :datakey="'items'"
        :onColumnsChange="columns => (this.columns = columns)"
        :onRowSelectChange="selectChange"
        height="auto"
        selectionType="single"
        :isSelectColumn=false
        :isPagination = false
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">添加</multiuse-button>
        </template>
      </FilterTable>
      <BaseDialog :visible.sync="visibleAdd" :title="'配件选择'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
        <PeiJianSelect @close="closeAdd" @save="saveAdd"></PeiJianSelect>
      </BaseDialog>
      <div
        :style="{
          position: 'absolute',
          left: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right'
        }"
      >
        <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
        <multiuse-button @click="closeDialog">关 闭</multiuse-button>
      </div>
    </Spin>
  </div>
</template>
<script>
import { getPartType,addOrders, selectListByPage ,preSaveList} from '@/api/claim/factory/PartsTypeMaintain';
import PeiJianSelect from '@/pages/claimDemage/tools/vehicle.vue';
import { getPart } from '@/api/dictionary/index';
export default {
  //  mixins: [dictionary],
  components: {
    PeiJianSelect
  },
  data() {
    return {
      visible: false,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      visibleAdd: false,
      obj: {
        rpPtTypeDTOS:[]
      },
      loading: false,
    };
  },
  created() {
    this.chuqi();
  },
  methods: {
    deleteFunweixiu(costItem) {
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE([costItem]);
      // this.feiyongformList.map(x => {
      //   if ('labourAmount' == x.fieldName) {
      //     x.initialValue = this.sumweixiufeiyongz - Number(costItem.cmsClaimAmount);
      //     this.sumweixiufeiyongz = this.sumweixiufeiyongz - Number(costItem.cmsClaimAmount)
      //     this.sumAmount();
      //   }
      // });
    },
    async chuqi(){
      const res = await getPart();
      if (res.resultCode == 200) {
        this.topFilterInit.find(x => x.fieldName == 'typeId').initialValue = '';
        this.topFilterInit.find(x => x.fieldName == 'typeId').itemList = res.data.map(y => ({ text: y.name, value: y.code }));
      }
      const res1 = await getPartType({ type: 5584 });
      if (res1.resultCode == 200) {
        this.topFilterInit.find(x => x.fieldName == 'operationType').itemList = res1.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd(val) {
      this.selectedRows = val;
      let falg = true ;

      this.$refs.table.$refs.pageTable.list.map(x => {
        if(val[0].partCode == x.partCode){
          falg = false;
          this.$notify.error({ title: '提示信息', message: '配件选择重复' });
        }
      });
      if(falg){
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(val);
      }
      this.visibleAdd = false;
    },
    //保存
    async saveDialog() {
      if (this.$refs.table.$refs.pageTable.list.length) {
        this.$refs.table.$refs.pageTable.list.map(x => {
          this.obj.rpPtTypeDTOS.push(x);
        });
        // this.obj.rpPtTypeDTOS = this.selectedRows;
        this.obj.rpPtTypeDTOS.map(x => {
          x.typeId = this.topFilterInit.find(x => x.fieldName == 'typeId').initialValue;
          x.operationType = this.topFilterInit.find(x => x.fieldName == 'operationType').initialValue;
          x.salesYear = this.topFilterInit.find(x => x.fieldName == 'salesYear').initialValue;
        });
        console.log(this.obj);
        if (!this.topFilterInit.find(x => x.fieldName == 'typeId').initialValue) {
          this.$notify.warning({title: '提示信息', message: '请选择配件类型' || '保存失败!'});
        } else {
          let res1 = await preSaveList(this.obj);
          if(res1.data){
            this.$confirm('此类型配件已存在是否更新?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(async() => {
                this.loading = true;
                let res = await addOrders(this.obj);
                if (res.resultCode === 200) {
                  this.$emit('save');
                  return this.$notify.success({title: '提示信息', message: '保存成功'});
                } else {
                  this.loading = false;
                  // this.$notify.error({title: '提示信息', message: res.errMsg || '保存失败!'});
                  // this.$emit('save');
                }
              })
              .catch(() => {});
          }else{
            let res = await addOrders(this.obj);
            console.log(res);
            if (res.resultCode === 200) {
              this.$emit('save');
              return this.$notify.success({title: '提示信息', message: '保存成功'});
            } else {
              this.loading = false;
              // this.$notify.error({title: '提示信息', message: res.errMsg || '保存失败!'});
              // this.$emit('save');
            }
          }

        }
      } else {
        return this.$notify.warning({title: '提示信息', message: '请添加配件列表!'});
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    topFilterInitFun() {
      return [
        {
          type: 'SELECT',
          label: '配件类型',
          fieldName: 'typeId',
          placeholder: '请选择配件类型...',
          initialValue: '',
          itemList: [],
          filterable: true,
          rules: [{ required: true, message: '请选择配件类型...', trigger: 'change' }],
        },
        {
          type: 'SELECT',
          label: '营运类型',
          fieldName: 'operationType',
          placeholder: '请选择营运类型...',
          initialValue: '',
          itemList: [],
          filterable: true,
          rules: [{ required: true, message: '请选择营运类型...', trigger: 'change' }],
        },{
          type: 'DATE',
          label: '销售年份',
          fieldName: 'salesYear',
          placeholder: '请输入电车保修年份...',
          dateType: 'year',
          initialValue: '',
          valueFormat: 'yyyy',
          rules: [{ required: true, message: '请选择销售年份...', trigger: 'change' }],
          unitRender: () => {
            return <span>(年)</span>;
          }
            },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          fixed: 'left',
          width: 80,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: (props, h) => {
            return (
              <div style="text-align:center">
              <multiuse-button  size="mini" type="text" onClick={() => this.deleteFunweixiu(props.row)}>
                删除
              </multiuse-button>
            </div>
          );
          }
        },
        { title: '配件名称', dataIndex: 'partName', sorter: true },
        { title: '配件代码', dataIndex: 'partCode', sorter: true },
        { title: '单位', dataIndex: 'partUnit', sorter: true }
      ];
    }
  }
};
</script>

<style lang="less" scoped></style>
